package com.inspur.edp.bef.bizentity.dboconsistencycheck;

import com.inspur.edp.bef.bizentity.GspBizEntityElement;
import com.inspur.edp.bef.bizentity.GspBizEntityObject;
import com.inspur.edp.bef.bizentity.GspBusinessEntity;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.databaseobject.api.entity.DatabaseObjectTable;
import io.iec.edp.caf.databaseobject.api.service.IDatabaseObjectRtService;
import org.springframework.util.StringUtils;

public class DboObjectCheck {
  protected GspBusinessEntity bizEntity;
  protected GspBizEntityObject bizEntityObject;
  protected DatabaseObjectTable databaseObject;
  protected StringBuffer expMessage;

  public DboObjectCheck(GspBusinessEntity bizEntity, GspBizEntityObject bizEntityObject) {
    this.bizEntity = bizEntity;
    this.bizEntityObject = bizEntityObject;
    this.expMessage = new StringBuffer();
}

  /**
   * BE节点校验
   * @return
   */
  public String checkObjCoincidence() {
    getRefObjectByName();
    if (this.bizEntityObject.getIsVirtual()) {
      return null;
    }
    if(!checkDboExist()) {
      return this.expMessage.toString();
    }
    this.bizEntityObject.getContainElements().forEach(ele -> {
      checkFieldCoincidence((GspBizEntityElement) ele);
    });
    return this.expMessage.toString();
  }

  /**
   * 获取BE对应DBO
   */
  private void getRefObjectByName() {
    String refObjectName = this.bizEntityObject.getRefObjectName();
    IDatabaseObjectRtService service = SpringBeanUtils.getBean(IDatabaseObjectRtService.class);
    this.databaseObject =(DatabaseObjectTable)service.getDatabaseObject(refObjectName);
  }

  /**
   * 数据库对象检查
   */
  private boolean checkDboExist() {
    if(this.databaseObject == null) {
      this.expMessage.append(getDBONotFoundMsg());
      return false;
    }
    return true;
  }
  /**
   * DBO信息
   */
  protected String getDBOInfo() {
    return String.format(DboCheckMessageUtil.DBOInfo, bizEntityObject.getRefObjectName());
  }
  /**
   * 业务实体信息
   * @return
   */
  protected String getBEInfo() {
    return getDBOInfo() + String.format(DboCheckMessageUtil.BEInfo,bizEntity.getName(),bizEntity.getCode());
  }

  /**
   * 实体节点信息
   * @return
   */
  protected String getObjectInfo() {
    return getBEInfo() + String.format(DboCheckMessageUtil.ObjectInfo, bizEntityObject.getName(),bizEntityObject.getCode());
  }



  /**
   * 数据库对象找不到
   * @return
   */
  private String getDBONotFoundMsg() {
    return DboCheckMessageUtil.DBONotFound + getObjectInfo() + DboCheckMessageUtil.NewLine + DboCheckMessageUtil.NewLine;
  }



  /**
   * 字段一致性校验
   * @param bizElement
   */
  private void checkFieldCoincidence(GspBizEntityElement bizElement) {
    DboFieldCheck checker = new DboFieldCheck(databaseObject, bizEntity,bizEntityObject, bizElement);
    String returnMsg = checker.checkFieldCoincidence();
    if(!StringUtils.isEmpty(returnMsg)){
      this.expMessage.append(returnMsg);
    }
  }


}
